﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace Framework.Core.Cryptography
{
    public sealed class AssymetricPublicKeyBuilder : IDisposable
    {
        private readonly RSACryptoServiceProvider rsa;

        public AssymetricPublicKeyBuilder(string application, string user)
            : this(new RsaCryptoServiceProviderFactory(), application, user)
        {
        }

        private AssymetricPublicKeyBuilder(IRsaCryptoServiceProviderFactory rsaCryptoServiceProviderFactory,
                                           string application,
                                           string user)
        {
            rsa = rsaCryptoServiceProviderFactory.Create(application, user);
        }

        public void Dispose()
        {
            ((IDisposable)rsa).Dispose();
        }

        public Stream ExportPublicKey(Stream stream)
        {
            var writer = new StreamWriter(stream);
            writer.Write(rsa.ToXmlString(false));
            writer.Flush();
            return stream;
        }
    }
}
